import storage from "@/common/function/storage";
import {
  verifyEmpty,
  getNextDayTimestamp,
  getReferenceObjectProperty,
} from "@/common/function";
import constants from "@/common/constants";
import { getUserInfo } from "@/api/user";
import { getModelList, createModel, updateModel } from "@/api";
import { getSearchFilter } from "@/common/function";

function updateStorage(key, val) {
  if (verifyEmpty(val)) storage.remove(key);
  else storage.set(key, val);
}

function getStateDefaultValue(state) {
  //获取state默认值
  return getReferenceObjectProperty(
    {
      token: null,
      openToken: null,
      userInfo: {},
    },
    state
  );
}

function setStateData(stateKey, storageKey) {
  // commit只能接收两个参数
  return function (state, { $assign = false, ...data }) {
    if ($assign) Object.assign(state[stateKey], data); //合并
    else state[stateKey] = data;
    storage.set("roleId", data?.roleId?.[0]);
    updateStorage(storageKey, state[stateKey]);
  };
}

// 获取该账号是否为服务人员
async function getServerData(creatorUserId) {
  let filterData = {
    currentPage: 1,
    pageSize: -1,
    filter: getSearchFilter({ creatorUserId }, { method: "eq" }),
  };
  const response = await getModelList("65c08a445efd5153ff55d908", filterData);
  storage.set("isServer", response?.data?.pagination?.total ? true : false);
}

// 查询用户信息
async function getUserInfoData(user_id) {
  let filterData = {
    currentPage: 1,
    pageSize: -1,
    filter: getSearchFilter({ user_id }, { method: "eq" }),
  };
  const { code, data } = await getModelList(
    "660247fe5efd5153ff56b807",
    filterData
  );
  console.log(code, data);
  if (data?.list?.length) {
    return data?.list?.[0];
  } else {
    throw "该用户未注册";
  }
}

// 创建用户信息
async function createUserInfoData(data) {
  console.log(data);
  try {
    await createModel("660247fe5efd5153ff56b807", data);
  } catch (error) {
    console.log(error);
  }
}

// 修改为最新用户信息

async function updateUserInfoData(data, userId) {
  let { headIcon, mobilePhone, realName, id: user_id } = data;

  try {
    await updateModel(
      "660247fe5efd5153ff56b807",
      { headIcon, mobilePhone, realName, user_id },
      userId
    );
  } catch (error) {
    console.log(error);
  }
}

const state = (() => {
  let lastLoginTime = uni.getStorageSync("lastLoginTime") || 0;
  let expirationTime = constants.LOGIN_EXPIRATION_TIME;
  let diffTime = 0;
  if (expirationTime !== Infinity) {
    if (constants.IS_MIDNIGHT) {
      diffTime = getNextDayTimestamp(1).timestamp - lastLoginTime; //获取次日凌晨时间戳与上次登录时间戳的差值
      diffTime = expirationTime - ONE_DAY + diffTime; //减去一天的毫秒数再加上差值
    } else {
      diffTime = Date.now() - lastLoginTime;
    }
  }
  const data = {};
  data.openToken = storage.get("OpenToken");
  if (diffTime <= expirationTime) {
    //登录时间戳没有过期
    data.token = storage.get("Token");
    if (data.token) {
      data.userInfo = storage.get("UserInfo");
    }
  } else if (lastLoginTime) {
    storage.clear();
  }
  return getStateDefaultValue(data);
})();

export default {
  namespaced: true,
  state,
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      uni.setStorageSync("lastLoginTime", Date.now());
      updateStorage("Token", token);
    },
    SET_USER_INFO: setStateData("userInfo", "UserInfo"),
    SET_OPEN_TOKEN(state, token) {
      state.openToken = token;
      updateStorage("OpenToken", token);
    },
    CLEAR_ALL_DATA(state) {
      Object.assign(state, getStateDefaultValue({}));
      storage.clear();
    },
  },
  actions: {
    async updateUserInfo({ commit }, token) {
      if (token) commit("SET_TOKEN", token);
      try {
        const info = await getUserInfo();
        // console.log("info", info);
        if (info?.code !== 200) throw null;
        await getServerData(info?.data?.id);
        getUserInfoData(info?.data?.id).then(
          async (res) => {
            let { headIcon, mobilePhone, realName, id: user_id } = info?.data;
            await updateUserInfoData(
              {
                headIcon,
                mobilePhone,
                realName,
                user_id,
              },
              res._id
            );
          },
          async (err) => {
            console.log("未注册", err);
            let { headIcon, mobilePhone, realName, id: user_id } = info?.data;
            await createUserInfoData({
              headIcon,
              mobilePhone,
              realName,
              user_id,
            });
          }
        );
        commit("SET_USER_INFO", info?.data);
        // 发送请求获取技师信息
        return info;
      } catch (error) {
        return Promise.reject({ code: 400, error });
      }
    },
    // 退出登录
    logout({ commit }) {
      commit("CLEAR_ALL_DATA");
    },
  },
};
